<template>
	<el-form :model="form" :rules="rules" ref="ruleForm" label-width="100px">
		<el-form-item label="旧密码" prop="oldPassword">
			<el-input
				v-model.trim="form.oldPassword"
				maxlength="16"
				show-word-limit
				clearable
				placeholder="请输入旧密码"
			></el-input>
		</el-form-item>
		<el-form-item label="新密码" prop="newPassword">
			<el-input
				v-model.trim="form.newPassword"
				maxlength="16"
				show-word-limit
				clearable
				placeholder="请输入新密码"
			></el-input>
		</el-form-item>
		<el-form-item label="确认新密码" prop="confirmPassword">
			<el-input
				v-model.trim="form.confirmPassword"
				maxlength="16"
				show-word-limit
				clearable
				placeholder="确认新密码"
			></el-input>
		</el-form-item>
		<el-form-item>
			<el-button type="primary" :loading="loading" @click="onSubmit()">保存</el-button>
		</el-form-item>
	</el-form>
</template>

<script lang="javascript">
	import { reactive, toRefs, onMounted, getCurrentInstance } from 'vue';
	import { isPassword } from '@/utils/validate';
	export default {
		setup () {
			let ruleForm = null;
			let data = reactive({
				loading : false,
				form : {
					oldPassword : '',
					newPassword : '',
					confirmPassword : ''
				},
				rules : {
					oldPassword : [
						{
							required : true,
							trigger : 'blur',
							message : '密码不能为空'
						}
					],
					newPassword : [
						{
							required : true,
							validator : (rule, value, callback) => {
								if (!isPassword(value)) {
									callback(new Error('数字,字母，特殊字符，任意2种组合(6-16)位'));
								} else {
									callback();
								}
							},
							trigger : 'blur'
						}
					],
					confirmPassword : [
						{
							required : true,
							validator : (rule, value, callback) => {
								if (!value) {
									callback(new Error('密码不能为空'));
								} else if (data.form.newPassword !== data.form.confirmPassword) {
									callback(new Error('2次密码不一致'));
								} else {
									callback();
								}
							},
							trigger : 'blur'
						}
					]
				}
			});
			onMounted(() => {
				ruleForm = getCurrentInstance().proxy.$refs['ruleForm'];
			});
			let onSubmit = () => {
				ruleForm.validate(async (valid) => {
					if (valid) {
						data.loading = true;
						try {
							console.log('update');
						} finally {
							data.loading = false;
						}
					}
				});
			};

			return {
				onSubmit,
				...toRefs(data)
			};
		}
	};
</script>

<style lang="scss" scoped></style>
